<template>
  <DialPlate :is-show-border="isEditing || !isRunning">
    <template v-slot:time-left>
      <SettingCircleButton />
      <StartCircleButton v-if="!isEditing && !isRunning" @click="startTimer()" />
      <RestartCircleButton v-if="!isEditing && isRunning" @click="resetTimer()" />
    </template>
    <template v-slot:time-box>
      <!-- 输入框 -->
      <div class="time-input-box" v-if="isEditing">
        <!-- 小时输入 -->
        <input ref="hoursInput" class="time-input" :style="{color: configStore.config.color, borderBottomColor: configStore.config.color, caretColor: configStore.config.color}" type="number" min="00" max="99" v-model.number="inputHours"
          @focus="validateInput()" />
        <span class="separator" :style="{color: configStore.config.color}">:</span>
        <!-- 分钟输入 -->
        <input ref="hoursInput" class="time-input" :style="{color: configStore.config.color, borderBottomColor: configStore.config.color}" type="number" min="0" max="59" v-model.number="inputMinutes"
          @focus="validateInput()" />
        <span class="separator" :style="{color: configStore.config.color}">:</span>
        <!-- 秒数输入 -->
        <input ref="hoursInput" class="time-input" :style="{color: configStore.config.color, borderBottomColor: configStore.config.color}" type="number" min="0" max="59" v-model.number="inputSeconds"
          @focus="validateInput()" />
      </div>
      <div class="stopwatch-box" :style="{color: configStore.config.color}" v-else>
        {{ formattedTime }}
      </div>
    </template>
    <template v-slot:time-right>
      <ChangeCircleButton routerUrl="/timer/clock" v-if="!isEditing && !isRunning" />
      <EditCircleButton @click="startEdit()" v-if="!isEditing && !isRunning && !isPausing" />
      <OkCircleButton @click="confirmEdit()" v-if="isEditing && !isRunning" />
      <StopCircleButton @click="stopTimer()" v-if="!isEditing && (isRunning || isPausing)" />
      <PauseCircleButton @click="pauseTimer()" v-if="!isEditing && isRunning" />
    </template>
  </DialPlate>
</template>

<script setup lang="ts">
import DialPlate from '@renderer/components/dialPlate/DialPlate.vue'
import SettingCircleButton from '@renderer/components/button/SettingCircleButton.vue'
import ChangeCircleButton from '@renderer/components/button/ChangeCircleButton.vue'
import EditCircleButton from '@renderer/components/button/EditCircleButton.vue'
import OkCircleButton from '@renderer/components/button/OkCircleButton.vue'
import StartCircleButton from '@renderer/components/button/StartCircleButton.vue'
import RestartCircleButton from '@renderer/components/button/RestartCircleButton.vue'
import StopCircleButton from '@renderer/components/button/StopCircleButton.vue'
import PauseCircleButton from '@renderer/components/button/PauseCircleButton.vue'
import { computed, ref } from 'vue'
import { useConfigStore } from '@renderer/stores/configStore';

const configStore = useConfigStore()

let inputHours = ref<string>('00') // 小时输入框
let inputMinutes = ref<string>('00') // 分钟输入框
let inputSeconds = ref<string>('00') // 秒数输入框
let isEditing = ref<boolean>(false) // 是否在编辑状态中
let isRunning = ref<boolean>(false) // 是否在计时中
let isPausing = ref<boolean>(false) // 是否在暂停中
let timeLeft = ref<number>(0) // 剩余时间
let originalTime: number = 0 // 原始时间
let lastUpdate = ref<number>(0) // 最后更新时间戳
let interval: NodeJS.Timeout | null = null // 定时器

// 格式化显示时间（处理正负计时）
const formattedTime = computed(() => {
  const totalSeconds = Math.abs(timeLeft.value)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60
  const sign = timeLeft.value < 0 ? '-' : ''

  return `${sign}${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`
})

// 补零函数（私有）
function padZero(num: number): string {
  return num.toString().padStart(2, '0')
}

// 启动计时器
function startTimer() {
  if (isRunning.value) return
  isRunning.value = true
  isPausing.value = false
  lastUpdate.value = Date.now()
  interval = setInterval(() => {
    const now = Date.now()
    const elapsedSeconds = Math.floor((now - lastUpdate.value) / 1000)
    if (elapsedSeconds > 0) {
      // 处理倒计时和正计时
      timeLeft.value = timeLeft.value > 0 ? Math.max(0, timeLeft.value - elapsedSeconds) : timeLeft.value - elapsedSeconds
      lastUpdate.value = now
    }
  }, 200)
}

function stopTimer() {
  pauseTimer()
  timeLeft.value = originalTime
  isPausing.value = false
}

// 暂停计时器
function pauseTimer() {
  if (!isRunning.value) return
  isRunning.value = false
  isPausing.value = true
  if (interval) {
    clearInterval(interval)
    interval = null
  }
}

// 重置计时器
function resetTimer() {
  pauseTimer()
  timeLeft.value = originalTime
  startTimer()
}

// 开始编辑
function startEdit() {
  isEditing.value = true
  isRunning.value = false
  isPausing.value = false
  // stopTimer()
  const total = Math.abs(timeLeft.value)
  inputHours.value = Math.floor(total / 3600).toString()
  inputMinutes.value = Math.floor((total % 3600) / 60).toString()
  inputSeconds.value = (total % 60).toString()
  validateInput()
}

// 确认编辑
function confirmEdit() {
  validateInput()
  const hours = parseInt(inputHours.value) || 0
  const minutes = parseInt(inputMinutes.value) || 0
  const seconds = parseInt(inputSeconds.value) || 0
  // 计算总秒数
  const totalSeconds = hours * 3600 + minutes * 60 + seconds
  timeLeft.value = totalSeconds
  originalTime = totalSeconds
  isEditing.value = false
}

// 输入验证，并补足不足两位的数字
function validateInput() {
  const inputs = [inputHours, inputMinutes, inputSeconds]
  const ranges = [
    [0, 99],
    [0, 59],
    [0, 59]
  ]
  let flag = true

  inputs.forEach((input, index) => {
    const value = parseInt(input.value)
    const range = ranges[index]

    if (!(value >= range[0] && value <= range[1])) {
      input.value = '00'
      flag = false
    } else if (value === 0) {
      input.value = '00'
    } else if (value < 10) {
      input.value = '0' + value
    }
  })
  return flag
}
</script>

<style lang="scss" scoped>
@font-face {
  font-family: 'Inconicso-Bold';
  src: url('../assets/font/Inconsolata-Bold-3.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

.time-input-box {
  display: flex;
  align-items: center;
  justify-content: center;

  .time-input {
    width: 26px;
    height: 30px;
    font-size: 20px;
    font-family: 'Inconicso-Bold';
    text-align: center;
    border: none;
    opacity: 0.7;
    border-bottom-width: 1px;
    border-bottom-style: solid;
    outline: none;
    background-color: transparent;

    &:focus {
      opacity: 1;
    }
  }

  .time-input::-webkit-outer-spin-button,
  .time-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .separator {
    margin: 0 4px;
    font-weight: bold;
  }
}

.stopwatch-box {
  font-family: 'Inconicso-Bold';
  font-size: 24px;
}
</style>
